<template>
	<view>
		<view class="cu-bar bg-white">
			<view class="action">图片上传</view>
			<view class="action">{{ imgList.length }}/{{ max }}</view>
		</view>
		<view class="cu-form-group padding-top">
			<view class="grid col-4 grid-square flex-sub">
				<view class="bg-img" v-for="(item, ind) in imgList" :key="ind" @tap="ViewImage" :data-url="item.fileUrl">
					<image :src="item.fileUrl" mode="aspectFill"></image>
					<view class="cu-tag bg-red" @tap.stop="DelImg(index, ind)" :data-index="ind"><text class="cuIcon-close"></text></view>
				</view>
				<view class="solids" @tap="ChooseImage(index)" v-if="imgList.length < max"><text class="cuIcon-cameraadd"></text></view>
			</view>
			<view ref="input" class="input" hidden="true"></view>
		</view>
	</view>
</template>

<script>
var sMD5 = require('common/js/md5.js');
import { mapState, mapActions} from 'vuex';
export default {
	data() {
		return {
			// 图片列表
			imgList: [],
			
			// 需要删除的元素
			needDel: [],
			// 
			res: {},
			cind: ""
		};
	},
	props: {
		// 图片名称
		bizKey: {
			type: String,
			default: ''
		},
		// 最大可上传数量 默认为4
		max: {
			type: Number,
			default: 4
		}
	},
	watch: {
		// 当图片列表发生变化的时候，需要通知父组件
		imgList() {
			let result = {};
			result.normal = this.imgList.map(item => {
				return item.id;
			});
			result.del = this.needDel;
			this.$emit('addOrDel', result);
		}
	},
	computed: {
		...mapState(['HOST_URL', 'sessionId'])
	},
	mounted() {
		
		// H5端图片上传
		// #ifdef H5
		var that = this;
		var input = document.createElement('input');
		input.type = 'file';
		input.id = 'imagesAll';
		input.accept = 'image/*';
		input.style.display = 'none';
		input.onchange = event => {
			that.uploadImgH5();
		};
		this.$refs.input.$el.appendChild(input);
		// #endif
	},
	methods: {
		...mapActions(["autoLogin"]),
		// 图片预览
		ViewImage(e) {
			var arr = [];
			this.imgList.forEach(data => {
				arr.push(data.fileUrl);
			});
			uni.previewImage({
				urls: arr,
				current: e.currentTarget.dataset.url
			});
		},
		// 微信/APP文件上传
		uploadImg(res,size) {
				var that = this;
				var rnd = new Date().getTime() + this.sessionId;
				
				// 获取文件后缀名
				var index1 = res.lastIndexOf('.');
				var index2 = res.length;
				var suffix = res.substring(index1, index2); //后缀名

				uni.showLoading({
					title: '上传中...',
					icon: 'none'
				});
				uni.uploadFile({
					url: this.HOST_URL + '/a/file/upload?__ajax=json&__sid=' + that.sessionId,
					filePath: res,
					name: 'file',
					formData: {
						fileMd5: rnd,
						bizKey: '',
						bizType: this.bizType,
						uploadType: 'image',
						imageMaxWidth: 1024,
						imageMaxHeight: 768,
						__ajax: 'json',
						fileName: rnd + suffix,
						id: 'WU_FILE_0',
						name: rnd + suffix,
						type: 'image/' + suffix.replace('.', ''),
						size: size
					},
					header: {
						'content-type': 'multipart/form-data'
					},
					success: res => {
						let result = JSON.parse(res.data);
						if(result.result == "login"){
							that.autoLogin().then(function(){
								that.uploadImg(res, size);
							})
						}
						if (result.result == 'true') {
							result.fileUpload.fileUrl = that.HOST_URL + result.fileUpload.fileUrl;
							var obj = {};
							obj.id = result.fileUpload.id;
							obj.fileUrl = result.fileUpload.fileUrl;
							that.imgList.push(obj);
						}
					},
					fail: err => {
						uni.showToast({
							title: "上传失败",
							icon: 'none'
						})
						console.log('fail');
						console.log(err);
					},
					complete: complete => {
						uni.hideLoading();
						console.log('complete');
						console.log(complete);
					}
				});
		},
		// 选择图片
		ChooseImage(ind) {
			// #ifdef H5
			document.getElementById('imagesAll').click();
			// #endif
			// #ifdef APP-PLUS || MP-WEIXIN
			var that = this;
			uni.chooseImage({
				count: that.max - that.imgList.length, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				// sourceType: ['album'], //从相册选择
				success: res=> {
					// 开始上传选中的图片
					res.tempFilePaths.forEach((value, ind)=>{
						that.uploadImg(value,res.tempFiles[ind].size);
					})
				},
				fail: res => {
					// 失败 用户取消的回调
				}
			});
			// #endif
		},
		// H5文件上传
		uploadImgH5() {
			// #ifdef H5
			var fData = new FormData();
			let imagesAll = document.getElementById('imagesAll');
			var index1 = imagesAll.value.lastIndexOf('.');
			var index2 = imagesAll.value.length;
			var suffix = imagesAll.value.substring(index1, index2); //后缀名
			fData.append('file', imagesAll.files[0]);
			fData.append('fileMd5', new Date().getTime() + this.sessionId);
			fData.append('bizKey', '');
			fData.append('bizType', this.bizType);
			fData.append('uploadType', 'image');
			fData.append('imageMaxWidth', 1024);
			fData.append('imageMaxHeight', 768);
			fData.append('fileName', new Date().getTime() + this.sessionId + suffix);
			fData.append('id', 'WU_FILE_0');
			fData.append('name', new Date().getTime());
			fData.append('type', 'image/' + suffix.replace('.', ''));
			fData.append('size', imagesAll.size);
			var xhr = new XMLHttpRequest();
			xhr.open('POST', this.HOST_URL + '/a/file/upload?__ajax=json&__sid=' + this.sessionId, true);
			let that = this;
			xhr.onreadystatechange = function() {
				console.log(xhr.readyState);
				if (xhr.readyState == 4) {
					var result = JSON.parse(xhr.responseText);
					if (result.result == 'true') {
						result.fileUpload.fileUrl = that.HOST_URL + result.fileUpload.fileUrl;
						var obj = {};
						obj.id = result.fileUpload.id;
						obj.fileUrl = result.fileUpload.fileUrl;
						that.imgList.push(obj);
						imagesAll.value = '';
					}
				}
			};
			//上传成功
			xhr.send(fData);
			// #endif
		},
		// 图片删除
		DelImg(index, ind) {
			uni.showModal({
				title: '',
				content: '确定要删除吗？',
				cancelText: '取消',
				confirmText: '确定',
				success: res => {
					if (res.confirm) {
						let obj = this.imgList.splice(ind, 1);
						this.needDel.push(obj[0].id);
					}
				}
			});
		}
	}
};
</script>
<style></style>
